package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.bussiness.recharge.GoldTokenBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.SortedMap;

@WebServlet(urlPatterns = "/buyGoldToken")
public class BuyGoldToken extends BaseJsonHttpServlet {

	private static Logger logger = LogManager.getLogger(BuyGoldToken.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("request buyGoldToken");
		HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
		JSONObject paramObj = httpJsonWebParam.getParamObj();
		String orderNo;
		String openId;
		String platformUserId;
		long userId;
		long money;
		long time;
		String sign;
		try{
			orderNo = paramObj.getString("order_id");
			platformUserId = paramObj.getString("user_id");
			userId = paramObj.getLongValue("role_id");
			time = paramObj.getLongValue("time");
			money = paramObj.getLongValue("money");
			sign = paramObj.getString("sign");
		} catch (Exception e) {
			logger.error("buyGoldToken args error:" + e);
			sendResult(response, 0, "args error");
			return;
		}
		if(money <= 0){
			logger.error("buyGoldToken money error,money:{}", money);
			sendResult(response, 0, "money error");
			return;
		}
		try{
			SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
			if(!SignHelper.checkSign(paramMap, AppKeyMgr.getAndroidAppSecret(), sign)){
				if(ServerListMgr.isCnMergeServer(WebServer.getInstance().getServerId())){
					if(!SignHelper.checkSign(paramMap, ChannelConfig.APP_SECRET_CONFIG, sign)){
						logger.error("buyGoldToken sign error");
						sendResult(response, 0, "sign error");
						return;
					}
				}else {
					logger.error("buyGoldToken sign error");
					sendResult(response, 0, "sign error");
					return;
				}
			}
			if(GoldTokenBussiness.checkGoldTokenOrder(orderNo)){
				logger.error("buyGoldToken orderNo already exist,orderNo:{}", orderNo);
				sendResult(response, 0, "orderNo already exist");
				return;
			}
			UserInfo userInfo = UserBussiness.getUserInfoByUserId(userId);
			if (null == userInfo) {
				logger.error("buyGoldToken user no find,orderNo:{},userId{}", orderNo, userId);
				sendResult(response, 0, "role no find");
				return;
			}
			if (!Objects.equals(userInfo.getPlatformUserId(), platformUserId)) {
				logger.error("buyGoldToken userId error,orderNo:{},platformUserId:{},order platformUserId:{}", orderNo,
						userInfo.getPlatformUserId(), platformUserId);
				sendResult(response, 0, "dirty userId");
				return;
			}
			if (!GoldTokenBussiness.addGoldTokenOrder(orderNo, userId, money, time)) {
				logger.error("buyGoldToken db add order fail,orderNo:{},userId:{},money:{},time:{}", orderNo, userId, money, time);
				sendResult(response, 0, "db add order fail");
				return;
			}
			GameWebServiceInvoke.notifyRechargeSuccess(orderNo, 2);
			sendResult(response, 1, "success");
		} catch (Exception e) {
			logger.error("buyGoldToken error:" + e);
			sendResult(response, 0, "other error");
		}
	}
}
